package com.warmheart.core.pool;

import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.annotation.Immutable;

import com.warmheart.core.ex.ServerException;

@Immutable
public class PoolResult<T> {

    private static final Logger logger = LoggerFactory.getLogger(PoolResult.class);

    private WhScfInfo<T> whScfInfo;

    private T t;

    protected PoolResult() {
    }

    protected PoolResult(WhScfInfo<T> whScfInfo) {
        this.whScfInfo = whScfInfo;
    }

    static <T> PoolResult.Builder<T> custom(@NotNull WhScfInfo<T> whScfInfo) {
        return new Builder<T>(whScfInfo);
    }

    static class Builder<T> {

        private WhScfInfo<T> whScfInfo;

        private Builder(WhScfInfo<T> whScfInfo) {
            super();
            this.whScfInfo = whScfInfo;
        }

        public PoolResult<T> build() {
            return new PoolResult<T>(this.whScfInfo);
        }
    }

    WhScfInfo<T> getWhScfInfo() {
        return this.whScfInfo;
    }

    /**
     * 
     * @Title: handlerResult
     * @Description: 处理结果
     * @author ZhangJianyang
     * @throws ServerException
     */
    void handlerResult() throws ServerException {
        T t;
        try {
            t = this.whScfInfo.getFuture().get();
        } catch (Exception e) {
            logger.error("获取结果数据失败", e);
            throw new ServerException("获取结果数据失败");
        }
        this.t = t;
        if (this.whScfInfo.consumer() != null) {
            this.whScfInfo.consumer().accept(this.t);
        }
    }

    /**
     * 
     * @Title: getT
     * @Description: 返回结果
     * @author ZhangJianyang
     * @return
     */
    public T getResult() {
        return t;
    }
}
